/**
 * Created by levy on 2016/12/15
 */
import React from 'react'
import {withRouter} from 'react-router'
import mui from '../../../lib/js/mui'
import {getUserId, ajax} from '../util'
import Loading from './Loading'
import Header from './Header'

const userId = getUserId()

@withRouter
export default class TaskList extends React.Component {
    state = {
        todoList: [],
        applyList: [],
        invokedList: [],
        loading: true
    }
    componentDidMount() {

        this.getTodoList()

        //apply
        ajax({
            url: '/workflow/api/v1/process-instance/user/' + userId + '?size=999',
            success: data => {
                this.setState({applyList: data.dataList})
            }
        }, null, err => {
            this.setState({loading: false})
            mui.toast('服务器正忙')
        })

        //invoked
        ajax({
            url: '/workflow/api/v1/process-involve/user/' + userId + '?size=999',
            success: data => {
                this.setState({invokedList: data.dataList})
            }
        }, null, err => {
            this.setState({loading: false})
            mui.toast('服务器正忙')
        })


        // fetch(config.apiPrefix + '/workflow/api/v1/task/userId_v2/' + config.userId + '?' + config.token,{
        //     mode: 'no-cors'
        // }).then(function(response) {
        //     return response.json().then(function(json) {
        //         alert('json')
        //     });
        // });
    }


    render() {

        return (
            <div>
                <Header title="我的任务"/>
                <div className="mui-content">
                    <div style={{padding: 10}}>
                        <div id="segmentedControl" className="mui-segmented-control">
                            <a className="mui-control-item mui-active" href="#todoList">
                                我的待办
                            </a>
                            <a className="mui-control-item" href="#applyList">
                                我发起的
                            </a>
                            <a className="mui-control-item" href="#invokedList">
                                我参与的
                            </a>
                        </div>
                    </div>
                    { this.renderTodoList() }
                    { this.renderApplyList() }
                    { this.renderInvokedList()}
                </div>
                <Loading loading={this.state.loading}/>
            </div>
        )
    }
    // TODO onClick在手机里可能无效
    renderTodoList = () => {
        return (
            <div id="todoList" className="mui-control-content mui-active">
                <ul className="mui-table-view">
                    {
                        this.state.todoList.map(task => (
                            <li className="mui-table-view-cell" key={task.processInstanceId}
                                onClick={this.todoDetail.bind(this, !task.extraOptions.dealUserId, task.extraOptions.definitionName,
                                       task.taskId, task.processInstanceId, task.processDefinitionId)}>
                                <a className="mui-navigate-right">
                                  {task.extraOptions.definitionName+'(发起人: '+task.extraOptions.applyManName+')'}
                                </a>
                            </li>
                        ))
                    }
                    {
                        !this.state.loading && !this.state.todoList.length ? <li className="mui-table-view-cell">暂无数据</li> : null
                    }
                </ul>
            </div>
        )
    }
    renderApplyList = () => {
        return (
            <div id="applyList" className="mui-control-content ">
                <ul className="mui-table-view">
                    {
                        this.state.applyList.map(task => (
                            <li className="mui-table-view-cell" key={task.processInstanceId}>
                                <a className="mui-navigate-right" onClick={this.detail.bind(this, task.title,
                                    task.taskId, task.processInstanceId, task.processDefinitionId)}>
                                    {task.title+'(当前处理人: '+task.dealPersonName+')'}
                                </a>
                            </li>
                        ))
                    }
                    {
                        !this.state.loading && !this.state.applyList.length ? <li className="mui-table-view-cell">暂无数据</li> : null
                    }
                </ul>
            </div>
        )
    }
    renderInvokedList = () => {
        return (
            <div id="invokedList" className="mui-control-content ">
                <ul className="mui-table-view">
                    {
                        this.state.invokedList.map(task => (
                            <li className="mui-table-view-cell" key={task.processInstanceId}>
                                <a className="mui-navigate-right" onClick={this.detail.bind(this, task.title,
                                     task.taskId, task.processInstanceId, task.processDefinitionId)}>
                                    {task.title+'(当前处理人: '+task.dealPersonName+')'}
                                </a>
                            </li>
                        ))
                    }
                    {
                        !this.state.loading && !this.state.invokedList.length ? <li className="mui-table-view-cell">暂无数据</li> : null
                    }
                </ul>
            </div>
        )
    }
    getTodoList = () => {
        // todoList
        ajax({
            url: '/workflow/api/v1/task/user_v2/' + userId + '?size=999',
            success: data => {
                this.setState({todoList: data.dataList, loading: false})
            }
        }, null, err => {
            this.setState({loading: false})
            mui.toast('服务器正忙')
        })
    }
    todoDetail(shouldClaim, title, taskId, processInstanceId, processDefinitionId) {
        let that = this,
            hasConfirm = false

        if (shouldClaim) {
            // FIXME mui的callback会触发两次, 不知什么原因
            mui.confirm('该任务需要先签收才能处理, 确定签收吗?', '提示', ['否', '是'], function(e) {
                if (!hasConfirm) {
                    hasConfirm = true
                    if (e.index == 1) {
                        ajax({
                            url: `/workflow/api/v1/task-claim/${taskId}/user/${userId}`,
                            success: function(data) {
                                if (data.msg == 'ok') {
                                    mui.toast('签收成功')
                                    setTimeout(function () {
                                        that.getTodoList()
                                    }, 300)
                                }
                            }
                        })
                    }
                    else
                        console.debug('选择了否')
                }
            })
        }
        else {
            this.detail(title, taskId, processInstanceId, processDefinitionId, 'todo')
        }
    }

    detail(title, taskId, processInstanceId, processDefinitionId, type){
        this.props.router.push({
            pathname: 'task-detail',
            query: {
                title: title,
                taskId: taskId,
                processInstanceId: processInstanceId,
                processDefinitionId: processDefinitionId,
                type: type.toString() // 待办时是todo, 另外两种情况会是event对象
            }
        })
    }
}
